package edu.office.applicationRepository;

import edu.office.entities.Edgeamongsubject;
import edu.office.entities.Subject;
import edu.office.tools.StaticFields;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Named("edgeamongsubjectRepositoryA")
@ApplicationScoped
public class EdgeamongSubjectRepository extends ApplicationCommonRepository<Edgeamongsubject> {
    @Inject
    SubjectRepository applicationSubjectController;

    public List<Edgeamongsubject> getEdgeAmongSubject4SubjectPreOrSucc(Integer subjectId, int location) {
        return switch (location) {
            case StaticFields.PREDCESSOR -> find("SUCCESSORNODE", subjectId).list();
            case StaticFields.SUCCESSOR -> find("PREDECESSORNODE", subjectId).list();
            default -> null;
        };
    }

    public String MyCreate(Edgeamongsubject edgeamongknowledge) {
        String result;
        //检查该记录是否已经存在的一个解决办法是从edgeamongsubject检查对应的前驱与后继
        //并放入SET中，然后从set中查找要create的记录，如果存在，则不create

        if (list("Predecessornode=?1 and Successornode=?2", edgeamongknowledge.getPREDECESSORNODE(),
                edgeamongknowledge.getSUCCESSORNODE()).isEmpty()) {
            create(edgeamongknowledge);
            result = "Succeed";
        } else {
            result = "Already Exist";
        }
        return result;
    }

    public void completePreSubjectSelection(Subject subject, String ids) {
        //原来的
        Set<Subject> existedSubjects_A = applicationSubjectController.getPredcessorSubject(subject);
        //现在的
        Set<Subject> nowSelectedSubjects_B = new HashSet<>(applicationSubjectController.find("select * from subject where id in(" + ids + ")").list());
        //得到要删除的
        Set<Subject> removedSubjects = new HashSet<>(existedSubjects_A);
        removedSubjects.removeAll(nowSelectedSubjects_B);
        //执行删除
        removedSubjects.forEach((subject1) -> {
            delete("delete from Edgeamongsubject where successornode=" + subject.getID()
                    + " and predecessornode=" + subject1.getID());
        });
        //得到要添加的
        nowSelectedSubjects_B.removeAll(existedSubjects_A);
        nowSelectedSubjects_B.forEach((Subject knowledge) -> {
            if (null != subject.getID()) {
                Edgeamongsubject edgeAmongknowledge = new Edgeamongsubject();
                edgeAmongknowledge.setSUCCESSORNODE(subject.getID());
                edgeAmongknowledge.setPREDECESSORNODE(knowledge.getID());
                create(edgeAmongknowledge);
            }
        });
    }
}
